package com.coda.service.impl;

import com.alibaba.fastjson.JSON;
import com.coda.Constant.MessageConstant;
import com.coda.common.Result;
import com.coda.context.BaseContext;
import com.coda.entity.Auth;
import com.coda.exception.BaseException;
import com.coda.mapper.AuthMapper;
import com.coda.mapper.UserMapper;
import com.coda.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AuthMapper authMapper;

    /**
     * 加载权限菜单
     *
     * @return
     */
    @Override
    public List<Auth> getauthList() {

        //现在redis中查询，如获取有直接返回
        String authTreeJson = (String) redisTemplate.opsForValue().get("authTree:" + BaseContext.getCurrentId());
        if (StringUtils.hasText(authTreeJson)) {
            //将redis中的redis中的json转换成list对象并返回
            List<Auth> authList = JSON.parseArray(authTreeJson, Auth.class);
            return authList;
        }

        //如果redis中没有该菜单树，则查询，再存储
        List<Auth> authList = userMapper.getAuthList(BaseContext.getCurrentId());
        //获取菜单树list
        List<Auth> authTreeList = getAuthTreeList(authList, 0l);
        //将菜单树存储进redis
        redisTemplate.opsForValue().set("authTree:" + BaseContext.getCurrentId(), JSON.toJSONString(authTreeList));
        return authTreeList;
    }

    /**
     * 根据权限名称查询权限
     * @param
     */
    @Override
    public Auth getAuthByName(String authName) {
        //根据名称查询权限
        Auth authInfo =  authMapper.getAuthByName(authName);
        return authInfo;
    }

    /**
     * 添加权限
     * @param auth
     */
    // todo 添加权限，已经从reids中删除了，但是新添加的权限显示不了
    @Override
    public void addAuth(Auth auth) {
        authMapper.addAuth(auth);
        //删除redis中的缓存
        redisTemplate.delete("authTree:"+BaseContext.getCurrentId());
    }


    /**
     * 递归获取菜单树
     */
    // todo 递归的理解
    private List<Auth> getAuthTreeList(List<Auth> authList, Long pid) {

        //创建list对象，用于存储每次递归获取的对象
        List<Auth> listAuth = new ArrayList<>();

        //遍历list对象
        for (Auth auth : authList) {
            //获取对应的authId并存储
            if (auth.getParentId() == pid) {
                listAuth.add(auth);
            }
        }

        //遍历auth对象
        for (Auth auth : listAuth) {
            //递归获取二级菜单，并添加
            List<Auth> childrenAuthList = getAuthTreeList(authList, auth.getAuthId());
            auth.setChildAuth(childrenAuthList);
        }
        return listAuth;
    }

}
